﻿/** EasyWeb iframe v3.1.5 date:2019-10-05 License By http://easyweb.vip */

// 用common.js必须加上Feng.addCtx("${ctxPath}");

// 通用方法封装处理
// 通用方法封装处理
Feng.common = {
    checkNull: function (value) {
        if (value == undefined || value == null || value == '') {
            return true;
        }
        return false;
    },
    // 判断字符串是否为空
    isEmpty: function (value) {
        if (!value || this.trim(value) == "") {
            return true;
        }
        return false;
    },
    // 判断一个字符串是否为非空串
    isNotEmpty: function (value) {
        return !$.common.isEmpty(value);
    },
    // 空对象转字符串
    nullToStr: function (value) {
        if ($.common.isEmpty(value)) {
            return "-";
        }
        return value;
    },
    // 是否显示数据 为空默认为显示
    visible: function (value) {
        if ($.common.isEmpty(value) || value == true) {
            return true;
        }
        return false;
    },
    // 空格截取
    trim: function (value) {
        if (!value) {
            return "";
        }
        return value.toString().replace(/(^\s*)|(\s*$)|\r|\n/g, "");
    },
    // 比较两个字符串（大小写敏感）
    equals: function (str, that) {
        return str == that;
    },
    // 比较两个字符串（大小写不敏感）
    equalsIgnoreCase: function (str, that) {
        return String(str).toUpperCase() === String(that).toUpperCase();
    },
    // 将字符串按指定字符分割
    split: function (str, sep, maxLen) {
        if ($.common.isEmpty(str)) {
            return null;
        }
        var value = String(str).split(sep);
        return maxLen ? value.slice(0, maxLen - 1) : value;
    },
    // 字符串格式化(%s )
    sprintf: function (str) {
        var args = arguments, flag = true, i = 1;
        str = str.replace(/%s/g, function () {
            var arg = args[i++];
            if (typeof arg === 'undefined') {
                flag = false;
                return '';
            }
            return arg;
        });
        return flag ? str : '';
    },
    // 指定随机数返回
    random: function (min, max) {
        return Math.floor((Math.random() * max) + min);
    },
    // 判断字符串是否是以start开头
    startWith: function (value, start) {
        var reg = new RegExp("^" + start);
        return reg.test(value)
    },
    // 判断字符串是否是以end结尾
    endWith: function (value, end) {
        var reg = new RegExp(end + "$");
        return reg.test(value)
    },
    // 数组去重
    uniqueFn: function (array) {
        var result = [];
        var hashObj = {};
        for (var i = 0; i < array.length; i++) {
            if (!hashObj[array[i]]) {
                hashObj[array[i]] = true;
                result.push(array[i]);
            }
        }
        return result;
    },
    // 数组中的所有元素放入一个字符串
    join: function (array, separator) {
        if ($.common.isEmpty(array)) {
            return null;
        }
        return array.join(separator);
    },
    // 获取form下所有的字段并转换为json对象
    formToJSON: function (formId) {
        var json = {};
        $.each($("#" + formId).serializeArray(), function (i, field) {
            json[field.name] = field.value;
        });
        return json;
    },
    convertFileSizeToKB: function (fileSize) {
        var result = fileSize;
        //根据文件大小做单位判断
        if (fileSize > Math.pow(1024, 2) && fileSize < Math.pow(1024, 3)) {
            var zs = Math.floor(fileSize / Math.pow(1024, 2));
            result = (zs + (fileSize % Math.pow(1024, 2) / Math.pow(1024, 2))).toFixed(2) + "M";
        } else if (fileSize > Math.pow(1024, 3)) {
            var zs = Math.floor(fileSize / Math.pow(1024, 3));
            result = (zs + (fileSize % Math.pow(1024, 3) / Math.pow(1024, 3))).toFixed(2) + "G";
        } else {
//			result = parseInt(fileSize/1024)
            result = Math.ceil(fileSize / 1024) + "kb";
        }
        return result;
    },
    convertKBToMG: function (sizekb) {
        var result = sizekb;
        //根据文件大小做单位判断
        if (sizekb > 1024 && sizekb < Math.pow(1024, 2)) {
            var zs = Math.floor(sizekb / 1024);
            result = (zs + (sizekb % 1024 / 1024)).toFixed(2) + "M";
        } else if (fileSize > Math.pow(1024, 2)) {
            var zs = Math.floor(sizekb / Math.pow(1024, 2));
            result = (zs + (sizekb % Math.pow(1024, 2) / Math.pow(1024, 2))).toFixed(2) + "G";
        } else {
//			result = parseInt(fileSize/1024)
            result = sizekb + "kb";
        }
        return result;
    },
}
Feng.openModal = function (options) {
    var _type = Feng.common.isEmpty(options.type) ? 2 : options.type;
    var _url = Feng.common.isEmpty(options.url) ? "/404.html" : options.url;
    var _title = Feng.common.isEmpty(options.title) ? "系统窗口" : options.title;
    var _width = Feng.common.isEmpty(options.width) ? "400" : options.width;
    var _height = Feng.common.isEmpty(options.height) ? (layui.jquery(window).height() - 50) : options.height;
    var _btn = ['<i class="layui-icon layui-icon-ok"></i> 确认', '<i class="layui-icon layui-icon-close"></i> 关闭'];
    if (Feng.common.isEmpty(options.yes)) {
        options.yes = function (index, layero) {
            options.callBack(index, layero);
        }
    }
    if (options.btn != false) {
        options.btn = true;
    }
    var layerOption = {
        type: _type,
        title: _title,
        area: [_width + 'px', _height + 'px'],
        content: _url,
        shadeClose: false,
        skin: options.skin,
        btn: options.btn ? _btn : false,
        success: options.success,
        yes: options.yes,
        end: options.end,
        cancel: options.end,
        btn2: function (index, layero) {}
    };
    if (options.offset) {
        layerOption['offset'] = options.offset;
    }
    var layerIndex = layer.open(layerOption);
    return layerIndex;
};
Feng.closeModalByIndex = function (layerIndex) {
    Feng.closeLoading();
    layer.close(layerIndex);
}
Feng.closeModal = function () {
    Feng.closeLoading();
    layer.close(layer.index);
}
Feng.loading = function () {
    top.layer.load();
};
Feng.closeLoading = function () {
    top.layer.closeAll('loading');
};
Feng.info = function (info) {
    top.layer.msg(info, {icon: 6});
};
Feng.success = function (info) {
    top.layer.msg(info, {icon: 1});
};
Feng.successCallback = function (info, callback) {
    top.layer.msg(info, {icon: 1}, function () {
        if (typeof callback == "function") {
            callback()
        }
    });
};

Feng.error = function (info) {
    Feng.closeLoading();
    top.layer.msg(info, {icon: 2});
};
Feng.alert = function (info) {
    top.layer.alert(info, {icon: 2});
};
Feng.confirm = function (tip, ensure) {
    top.layer.confirm(tip, {
        skin: 'layui-layer-admin'
    }, function (index) {
        ensure(index);
    });
};
Feng.confirmNoSkin = function (tip, ensure) {
    top.layer.confirm(tip, function (index) {
        ensure(index);
    });
};
Feng.topClose = function (index) {
    top.layer.close(index);
};
Feng.currentDate = function () {
    // 获取当前日期
    var date = new Date();

    // 获取当前月份
    var nowMonth = date.getMonth() + 1;

    // 获取当前是几号
    var strDate = date.getDate();

    // 添加分隔符“-”
    var seperator = "-";

    // 对月份进行处理，1-9月在前面添加一个“0”
    if (nowMonth >= 1 && nowMonth <= 9) {
        nowMonth = "0" + nowMonth;
    }

    // 对月份进行处理，1-9号在前面添加一个“0”
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }

    // 最后拼接字符串，得到一个格式为(yyyy-MM-dd)的日期
    return date.getFullYear() + seperator + nowMonth + seperator + strDate;
};
Feng.getUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    } else {
        return null;
    }
};
Feng.getUrlChineseParam = function(name) {
    var rs = new RegExp("(^|)" + name + "=([^&]*)(&|$)","gi").exec(window.document.location.href);
    if (rs != null && rs.length > 0) {
        return rs[2];
    }
    return null;
};
Feng.infoDetail = function (title, info) {
    var display = "";
    if (typeof info === "string") {
        display = info;
    } else {
        if (info instanceof Array) {
            for (var x in info) {
                display = display + info[x] + "<br/>";
            }
        } else {
            display = info;
        }
    }
    top.layer.open({
        title: title,
        type: 1,
        skin: 'layui-layer-rim', //加上边框
        area: ['950px', '600px'], //宽高
        content: '<div style="padding: 20px;">' + display + '</div>'
    });
};
Feng.closeAllLoading = function () {
    layer.closeAll('loading');
};
Feng.createSelect = function (select, data, value, text, defaultValue) {
    for (var i = 0; i < data.length; i++) {
        var selected = '';
        if (defaultValue && defaultValue === data[i][value]) {
            selected = 'selected';
        }
        select.append('<option value="' + data[i][value] + '" ' + selected + '>' + data[i][text] + '</option>');
    }
};
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};
Feng.getClientHeight = function () {
    var clientHeight = 0;
    if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
    } else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
    }
    return clientHeight;
};
Feng.getClientHeightPx = function () {
    return Feng.getClientHeight() + 'px';
};
Feng.pageLimit = function () {
    return 20;
};
/**数据模型中字典字段转换后的key后缀*/
Feng.getDicColumnKeySuffix = function() {
    return "DicValue";
};
/**
 * 过滤表头
 * @param tableUrl: 数据表格地址
 * @param cols：列
 */
Feng.filterCols = function (tableUrl, cols) {
    var ajax = new layui.ax(Feng.ctxPath + "/sys/user/column/getColumn");
    ajax.set({url: tableUrl});
    var result = ajax.start();
    var content = result.data;
    if (content.length > 0) {
        for (var i = 0; i < cols.length; i++) {
            if (cols[i]['hide'] == undefined || cols[i]['hide'] === false) {
                if (cols[i]['field'] === undefined) {
                    continue;
                }
                if (content.indexOf(',' + cols[i]['field'] + ',') < 0) {
                    cols[i]['hide'] = true;
                }
            }
        }
    }
    console.log(cols);
    return cols;
};
Feng.renderTable = function(templateCode, tableId, operatorWidth, queryParams) {
    var ajax = new layui.ax(Feng.ctxPath + '/rest/template/data/listColumn.api?templateCode=' + templateCode);
    var result = ajax.start();
    var tableColumn = [];
    tableColumn.push({type: 'numbers', title: '序号'});
    for (var i = 0; i < result.length; i++) {
        tableColumn.push({field: result[i].field, title: result[i].title, hide: result[i].hide});
    }
    tableColumn.push({align: 'center', toolbar: '#tableBar', title: '操作', width: operatorWidth});

    return layui.table.render({
        elem: '#' + tableId,
        url: Feng.ctxPath + '/rest/template/data/query.api',
        queryParams: queryParams,
        page: true,
        height: "full-98",
        limit: Feng.pageLimit(),
        cellMinWidth: 100,
        cols: [tableColumn]
    });
};

// 以下代码是配置layui扩展模块的目录，每个页面都需要引入
layui.config({
    version: Feng.version,
    base: Feng.ctxPath + '/assets/common/module/'
}).extend({
    formSelects: 'formSelects/formSelects-v4',
    treetable: 'treetable-lay/treetable',
    notice: 'notice/notice',
    step: 'step-lay/step',
    citypicker: 'city-picker/city-picker',
    tableSelect: 'tableSelect/tableSelect',
    Cropper: 'Cropper/Cropper',
    transferExt: 'transfer/transfer',
    introJs: 'introJs/introJs',
    fileChoose: 'fileChoose/fileChoose',
    tagsInput: 'tagsInput/tagsInput',
    Drag: 'Drag/Drag',
    Split: 'Split/Split',
    cascader: 'cascader/cascader',
    selectPlus: '../../expand/module/selectPlus/selectPlus',
    ax: '../../expand/module/ax/ax',
    iconPicker: '../../expand/module/iconPicker/iconPicker',
    func: '../../expand/module/func/func'
}).use(['layer', 'admin'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var admin = layui.admin;

    // 移除loading动画
    setTimeout(function () {
        admin.removeLoading();
    }, window == top ? 600 : 100);

    //注册session超时的操作
    $.ajaxSetup({
        contentType: "application/x-www-form-urlencoded;charset=utf-8",
        complete: function (XMLHttpRequest, textStatus) {

            //如果超时就处理 ，指定要跳转的页面
            if (XMLHttpRequest.getResponseHeader("Guns-Session-Timeout") === "true") {
                window.location = Feng.ctxPath + "/global/sessionError";
            }

        }
    });

});
